//
//  MessageViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/9/28.
//  Copyright © 2020 吴欧. All rights reserved.
//

#import "MessageViewController.h"
#import "HENavView.h"

#import "UILabel+ChangeFont.h"
#import "FMFontManager.h"
#import "UIFont+Addtion.h"
#import "ChangeFontManager.h"
#import "NextViewController.h"
#import "HEItemBtnView.h"
#import "HEIMMsgCell.h"
#import "HESysMsgCell.h"
#import "HEDocImMsgModel.h"
#import "HESysMsgModel.h"
#import "HEConsulInfoViewController.h"
#import "HESystemInfoViewController.h"
#import "HEIMChatViewController.h"
#import "HEIMTWChatViewController.h"
#import "HEIMTeamViewController.h"
#import "HEOrderDetailsViewController.h"
#import "HEActiveModel.h"
#import "HEActiveCell.h"
#import "HEActiveDetailsViewController.h"
#import "HEProxyPayCell.h"
#import "HEIMSickbedCell.h"
#import "HEIMGroupViewController.h"

@interface MessageViewController ()<UITableViewDelegate, UITableViewDataSource, HESocketManagerDelegate>

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray  * dataSourceArr;

@property (nonatomic, strong) HENavView *nav;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, assign) NSInteger sysInfoNum;
@property (nonatomic, assign) NSInteger askInfoNum;
@property (nonatomic, strong) HEItemBtnView *consulBtn;
@property (nonatomic, strong) HEItemBtnView *sysBtn;
@property(nonatomic, assign) BOOL needBackRefresh;

@end

@implementation MessageViewController

- (NSMutableArray  *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self getHasRead];
    
    if (self.needBackRefresh) {
        [self loadNewData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.zx_navBar.backgroundColor = CNavBgColor;
    self.zx_navLineView.hidden = YES;
    self.zx_navTitleColor = KWhiteColor;
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleLight;

    _pageNum = 1;
    _pageSize = 10;
    
    self.title = @"消息";
    
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    [self.view addSubview:self.tableView];
 
    self.view.backgroundColor = CLightGrayColor;
    
    [[HESocketManager sharedManager] addDelegate:self];
    
    [self initUI];
    [self initCell];

    [self initInfoWarp];

    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getHasRead) name:KNotificationRefreshNoReadMsg object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:KChangeFontNotification object:nil];
}

- (void)refresh {
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationRefreshNoReadMsg object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KChangeFontNotification object:nil];
}

- (void)initUI {
    CGFloat offestH = kStatusBarHeight - 20;
    HENavView *nav = [[HENavView alloc] init];
    [self.view addSubview:nav];
    _nav = nav;
    
    [nav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.equalTo(self.view);
        make.height.offset(130 + offestH);
    }];
    
    
    //
    [self zx_setRightBtnWithText:@"全部已读" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [self readAllMsg];
    }];
}

- (void)btnAction:(UIButton *)btn{
//    [[UserManager sharedUserManager] removeToken];
   
    [self presentViewController:[NextViewController new] animated:YES completion:nil];
}

- (void)initInfoWarp {
    UIView *infoWarp = [UIView new];
    infoWarp.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    infoWarp.layer.shadowColor = [UIColor colorWithRed:13/255.0 green:98/255.0 blue:218/255.0 alpha:0.08].CGColor;
    infoWarp.layer.shadowOffset = CGSizeMake(0,5);
    infoWarp.layer.shadowOpacity = 1;
    infoWarp.layer.shadowRadius = 6;
    infoWarp.layer.cornerRadius = 10;
    [self.view addSubview:infoWarp];
    
    [infoWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(ZXNavBarHeight);
        make.left.equalTo(self.view).offset(15);
        make.right.equalTo(self.view).offset(-15);
        make.height.offset(110);
    }];
    
    HEItemBtnView *allMsgBtn = [HEItemBtnView new];
    allMsgBtn.title = @"全部消息";
    allMsgBtn.imageName = @"message_all";
    allMsgBtn.titleColor = CNavLightBlackColor;
    allMsgBtn.titleFont = DYFont(17);
    [allMsgBtn resetLayoutWithWidth:45 height:45];
    KWeakSelf
    allMsgBtn.selectBlock = ^(HEItemBtnView * _Nonnull btn) {
    };
    [infoWarp addSubview: allMsgBtn];

    HEItemBtnView *consulBtn = [HEItemBtnView new];
    consulBtn.title = @"问诊消息";
    consulBtn.imageName = @"message_wz";
    consulBtn.titleColor = CNavLightBlackColor;
    consulBtn.titleFont = DYFont(17);
    [consulBtn resetLayoutWithWidth:45 height:45];
    
    consulBtn.selectBlock = ^(HEItemBtnView * _Nonnull btn) {
        HEConsulInfoViewController *vc = [HEConsulInfoViewController new];
        vc.backBlock = ^{
            [weakSelf refreshNewData];
        };
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    [infoWarp addSubview: consulBtn];
    _consulBtn = consulBtn;

    HEItemBtnView *sysBtn = [HEItemBtnView new];
    sysBtn.title = @"系统消息";
    sysBtn.imageName = @"message_system";
    sysBtn.titleColor = CNavLightBlackColor;
    sysBtn.titleFont = DYFont(17);
    [sysBtn resetLayoutWithWidth:45 height:45];
    sysBtn.selectBlock = ^(HEItemBtnView * _Nonnull btn) {
        HESystemInfoViewController *vc = [HESystemInfoViewController new];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    [infoWarp addSubview: sysBtn];
    _sysBtn = sysBtn;

    NSArray *arr = @[allMsgBtn, consulBtn, sysBtn];

    [arr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(infoWarp).offset(15);
        make.bottom.equalTo(infoWarp).offset(-15);
    }];
 
    [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:10 tailSpacing:10];
}

#pragma mark -
- (GDTableView *)tableView {
   if (!_tableView) {
       _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight + 110 + 15, KScreenWidth, KScreenHeight - (ZXNavBarHeight + 110 + 15 + 20)) style:UITableViewStyleGrouped];
       _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       _tableView.scrollsToTop = YES;
       _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
       _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

       _tableView.showsVerticalScrollIndicator = NO;
       _tableView.backgroundColor = CViewBgColor;
       _tableView.delegate = self;
       _tableView.dataSource = self;

       __weak __typeof(&*self)weakSelf = self;
       self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

           [weakSelf refreshNewData];
       }];

       self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
           weakSelf.isFromHeadRefresh = NO;
           weakSelf.pageNum += 1;
           [weakSelf loadData];
       }]; 
   }
   return _tableView;
}

- (void)initCell {
   // 总段
   _sections = [NSMutableArray array];
   NSMutableArray *classArr = [NSMutableArray array];
  
    GDFiterCellModel *imModel = [GDFiterCellModel new];
    imModel.cellKlass = HEIMMsgCell.class;
    
    GDFiterCellModel *sysModel = [GDFiterCellModel new];
    sysModel.cellKlass = HESysMsgCell.class;
    
    GDFiterCellModel *activeModel = [GDFiterCellModel new];
    activeModel.cellKlass = HEActiveCell.class;
 
    GDFiterCellModel *payModel = [GDFiterCellModel new];
    payModel.cellKlass = HEProxyPayCell.class;
    
    GDFiterCellModel *imSickbedModel = [GDFiterCellModel new];
    imSickbedModel.cellKlass = HEIMSickbedCell.class;
    
    classArr = @[imModel, sysModel, activeModel, payModel, imSickbedModel].mutableCopy;

   // 添加的时候注意顺序，暂未对顺序做处理
   [self.tableView mc_registerCellByFiterModels: classArr];
    
    [_tableView reloadData];
}

#pragma mark - loadData
- (void)loadData {
    HEPageRequest *req = [HEPageRequest new];
    req.pageNum = _pageNum;
    req.pageSize = _pageSize;
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KImhis parameters:req success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
       
        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
            [self.sections removeAllObjects];
        }
        
        [self dealData: response.data];
        [self.tableView reloadData];
 
        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (response.data.count == 0) {
                [Dialog toastBottom:@"没有更多数据了~"];
            }
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

// 分配cell类型
- (void)dealData:(NSArray *)arr {
    for (NSDictionary *dict in arr) {
        NSObject *item = nil;
        GDFiterCellModel *fiterModel = [GDFiterCellModel new];
        
        if ([@"im" isEqualToString: dict[@"message_type"]] ||
            [@"ask" isEqualToString: dict[@"message_type"]]) {
            item = [HEDocImMsgModel mj_objectWithKeyValues:dict];
            HEDocImMsgModel *model = (HEDocImMsgModel *)item;
            if ([@"3" isEqualToString:model.msgType]) {
                fiterModel.cellKlass = HEIMSickbedCell.class;
            }else {
                fiterModel.cellKlass = HEIMMsgCell.class;
            }
        }
        else {
            HESysMsgModel *info = [HESysMsgModel mj_objectWithKeyValues:dict];
            if (info.sysType == HESysInfoTypeACTIVITY) {
                item = (HEActiveModel *)info.params;
                fiterModel.cellKlass = HEActiveCell.class;
            }else if (info.sysType == HESysInfoTypeProxyPay) {
                item = info;
                fiterModel.cellKlass = HEProxyPayCell.class;
            }else {
                item = info;
                fiterModel.cellKlass = HESysMsgCell.class;
            }
        }
        
        [self.dataSourceArr addObject: item];
        [self.sections addObject: fiterModel];
    }
}
 
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   return _sections.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView dequeueReusableCellWithIdentifier:fiterModel.cellId];
    [cell configCellWithModel: _dataSourceArr[indexPath.row]];
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier: fiterModel.cellId cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        [cell configCellWithModel: self.dataSourceArr[indexPath.row]];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSObject *obj = self.dataSourceArr[indexPath.row];
    
    if ([HEDocImMsgModel.class isEqual: obj.class]) {
        HEDocImMsgModel *msg = (HEDocImMsgModel *)obj;
        
        if([@"ask" isEqualToString:msg.message_type]) {
            [self markTWRead: msg];
            [self intoTWChat: msg];
        }else if([@"im" isEqualToString:msg.message_type]){
            if ([@"0" isEqualToString:msg.msgType]) {
                [self markIMRead: msg];
                [self intoChat: msg];
            }else if ([@"1" isEqualToString:msg.msgType] ||
                      [@"3" isEqualToString:msg.msgType]) {
                [self markIMRead: msg];
                [self intoTeam: msg];
            }else if ([@"4" isEqualToString:msg.msgType]) {
                [self markIMRead: msg];
                [self intoGroup: msg];
            }
        }
    }
    else if ([HEActiveModel.class isEqual: obj.class]) {
        [self markActiveRead: (HEActiveModel *)obj];
        HEActiveDetailsViewController *vc = [HEActiveDetailsViewController new];
        vc.activeId = ((HEActiveModel *)obj).id;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        HESysMsgModel *msg = (HESysMsgModel *)obj;
        [self markSysRead: msg];
        
        switch (msg.sysType) {
            case HESysInfoTypeADD_NUM:
            {
                HEOrderModel *order = (HEOrderModel *)msg.params;
                HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
                vc.orderId = order.orderItemList.firstObject.orderId;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case HESysInfoTypeProxyPay:
            {
                HEProxyPayInfoModel *order = (HEProxyPayInfoModel *)msg.params;
                HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
                vc.orderId = order.order_id;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            default:
                break;
        }
    }
}

- (void)intoTeam:(HEDocImMsgModel *)msg{
    HEIMKitInfo *reciverInfo = [HEIMKitInfo new];
    HEIMUserModelType modelType = HEIMUserModelTypeTeamIM;
    if ([@"1" isEqualToString:msg.msgType]) {
        reciverInfo.infoId = msg.teamId;
        reciverInfo.showName = msg.teamName;
        modelType = HEIMUserModelTypeTeamIM;
    }else if ([@"3" isEqualToString:msg.msgType]){
        reciverInfo.infoId = msg.to;
        reciverInfo.showName = @"居家医养";
        modelType = HEIMUserModelTypeSickbed;
    }

    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[reciverInfo, owner]];

    HEIMTeamViewController *imVC = [HEIMTeamViewController new];
    imVC.teamId = reciverInfo.infoId;
    imVC.modelType = modelType;
    [self.navigationController pushViewController:imVC animated:YES];
}

- (void)intoTWChat:(HEDocImMsgModel *)msg {
    
    HEIMKitInfo *doc = [HEIMKitInfo new];
    doc.infoId = msg.user_id;
    doc.referenceId = msg.inst_id;
    doc.showName = msg.realname;
    doc.avatarUrlString = msg.avatar;
    doc.avatarImage = IMAGE_NAMED(@"hmang");
    
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[doc, owner]];
    
    KWeakSelf
    HEIMTWChatViewController *vc = [HEIMTWChatViewController new];
    vc.docId = msg.doc_id;
    vc.inst_id = msg.inst_id;
    vc.docName = msg.realname;
    vc.backBlock = ^{
        [weakSelf refreshNewData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)intoChat:(HEDocImMsgModel *)msg {
    HEIMKitInfo *doc = [HEIMKitInfo new];
    doc.infoId = msg.user_id;
    doc.showName = msg.realname;
    doc.avatarUrlString = msg.avatar;
    doc.avatarImage = IMAGE_NAMED(@"hmang");
    
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[doc, owner]];

    KWeakSelf
    HEIMChatViewController *imVC = [HEIMChatViewController new];
    imVC.docId = msg.user_id;
    imVC.isExprie = msg.privateExpire;
    imVC.backBlock = ^{
        [weakSelf refreshNewData];
    };
    [self.navigationController pushViewController:imVC animated:YES];
}


- (void)intoGroup:(HEDocImMsgModel *)msg{
    
    HEIMKitInfo *reciverInfo = [HEIMKitInfo new];
    reciverInfo.infoId = msg.to;
    reciverInfo.showName = msg.group_name;

    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[reciverInfo, owner]];

    HEIMGroupViewController *imVC = [HEIMGroupViewController new];
    imVC.teamId = reciverInfo.infoId;
    imVC.modelType = HEIMUserModelTypeGroup;
    [self.navigationController pushViewController:imVC animated:YES];
}

/// 标记图文医生已读
- (void)markTWRead:(HEDocImMsgModel *)msg {
    if(msg.is_read) {
        return;
    }
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KServiceRead parameters:@{@"inst_id" : msg.inst_id} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg. is_read = YES;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

/// 标记私人医生已读
- (void)markIMRead:(HEDocImMsgModel *)msg {
    if(msg.is_read) {
        return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if ([@"0" isEqualToString:msg.msgType]) {
        [dict setValue:msg.from_id forKey:@"doctor_id"];
    }else if([@"1" isEqualToString:msg.msgType]) {
        [dict setValue:msg.teamId forKey:@"doctor_id"];
    }else if([@"3" isEqualToString:msg.msgType] ||
             [@"4" isEqualToString:msg.msgType]) {
        [dict setValue:msg.to forKey:@"doctor_id"];
    }
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KimRead parameters:dict success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg.is_read = YES;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

/// 标记系统已读
- (void)markSysRead:(HESysMsgModel *)msg {
    if(msg.is_read) {
        return;
    }
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:Kreadmsg parameters:@{@"id" : [NSNumber numberWithInteger: msg.id]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg.is_read = YES;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

// 标记活动已读
- (void)markActiveRead:(HEActiveModel *)msg {
    if(!msg.showRead) {
        return;
    }
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:Kreadmsg parameters:@{@"id" : [NSNumber numberWithInteger: msg.msg_id]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg.showRead = NO;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark - HESocketManagerDelegate
- (void)onRecvMessages:(HEIMMessageModel *)message {
    [self refreshNewData];
}

- (void)onGroupMemberUpdate:(NSDictionary *)model {
    [self refreshNewData];
}

- (void)onGroupCreateAndDelUpdate:(NSDictionary *)model {
    [self refreshNewData];
}

- (void)refreshNewData {
    self.needBackRefresh = YES;
    if([self isVCVisable]){
        [self loadNewData];
    }
}

- (void)loadNewData {
    self.isFromHeadRefresh = YES;
    self.pageNum = 1;
    [self loadData];
    self.needBackRefresh = NO;
}

#pragma mark - 获取是否有未读
- (void)readAllMsg {
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KreadAllMsg parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [self getHasRead];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)getHasRead {
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KunReadMsg parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            NSNumber *sys_num = (NSNumber *)response.data[@"system_message"];
            NSNumber *ask_num = (NSNumber *)response.data[@"ask_message"];

            self.sysInfoNum = sys_num.integerValue;
            self.askInfoNum = ask_num.integerValue;
            
            if ((self.sysInfoNum + self.askInfoNum) > 0) {
                [self setupTabbarBadge];
            }else {
                [self.tabBarItem pp_hiddenBadge];
            }
            [self refreshNewData];
            [self refreRead];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)setupTabbarBadge {
    [self.tabBarItem pp_setBadgeHeight:16];
    [self.tabBarItem pp_moveBadgeWithX: 3 Y: 5];
    self.tabBarItem.badgeView.font = DYBlodFont(14);

    self.tabBarItem.badgeView.qmui_borderPosition = QMUIViewBorderPositionBottom | QMUIViewBorderPositionTop | QMUIViewBorderPositionLeft | QMUIViewBorderPositionRight;
    self.tabBarItem.badgeView.qmui_borderWidth = 2;
    self.tabBarItem.badgeView.qmui_borderColor = KWhiteColor;
}

- (void)refreRead {
    [self setupbadge: _consulBtn num: _askInfoNum];
    [self setupbadge: _sysBtn num: _sysInfoNum];
}

- (void)setupbadge:(UIView *)view num:(NSInteger)num {
    if (num == 0) {
        [view pp_hiddenBadge];
        return;
    }
    [view pp_showBadge];

    NSString *str = @"";
    if (num > 99) {
        str = @"99+";
    }else {
        str = [NSString stringWithFormat:@"%ld", num];
    }
    
    [view pp_setBadgeHeight:22];
    view.badgeView.font = DYBlodFont(14);
    
    view.badgeView.qmui_borderPosition = QMUIViewBorderPositionBottom | QMUIViewBorderPositionTop | QMUIViewBorderPositionLeft | QMUIViewBorderPositionRight;
    view.badgeView.qmui_borderWidth = 2;
    view.badgeView.qmui_borderColor = KWhiteColor;
    
    [view pp_addBadgeWithText:str];
    [view pp_moveBadgeWithX: -30 Y: 5];
}

@end
